package main

import (
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"strconv"
)

type Site struct {
	id    int
	title string
	url   string
	state int
}

type Sites []Site

type Dbconf struct {
	Host   string
	User   string
	Pwd    string
	DbName string
	Table  string
}

// 获得数据
func getSites() (sites Sites) {

	db, err := sql.Open("mysql", dbcon)
	defer db.Close()
	checkErr(err)

	rows, _ := db.Query("select id,title,url,state from " + conf.Database.Table)
	defer rows.Close()

	for rows.Next() {
		site := Site{}
		err = rows.Scan(&site.id, &site.title, &site.url, &site.state)
		sites = append(sites, site)
	}
	return
}

// 更新数据
func setSite(id int, state int) bool {

	db, err := sql.Open("mysql", dbcon)
	defer db.Close()
	checkErr(err)

	stmt, err := db.Prepare("update " + conf.Database.Table + " set state=? where id=?")
	checkErr(err)
	defer stmt.Close()
	res, err := stmt.Exec(strconv.Itoa(state), strconv.Itoa(id))
	checkErr(err)
	affect, err := res.RowsAffected()
	checkErr(err)
	if affect == 1 {
		return true
	}
	return false
}
